import json

from client import es_client
from dao.es_dao.card_dao import get_doc_by_imei, get_card
from client.redis_client import r


async def save_step_record(imei: str):
    source = json.loads(r.hget('state_' + imei, 'source'))
    step_list_from_redis = r.lrange('step_' + imei, 0, -1)
    step_list = []
    _id, card = await get_card(imei)
    if card is not None:
        for step_str in step_list_from_redis:
            step_json = json.loads(step_str)
            step_list.append(step_json)
        step_record_data = {
            "dt": source['dt'],
            "dataAuthority": source['dataAuthority'],
            "jobPost": card['jobPost'],
            "projectId": card['depart'],
            "projectName": card['departName'],
            "regionId": card['regionId'],
            "nickName": source['name'],
            "imei": imei,
            "step": step_list
        }
        if card['fullStep'] is not None:
            step_record_data['fullStep'] = card['fullStep']
        if card['depart'] is not None:
            step_record_data['projectId'] = card['depart']
        if card['departName'] is not None:
            step_record_data['projectName'] = card['departName']
        es = await es_client.get_es_client()
        await es.index_document('p_step_record', step_record_data)
        r.delete("step_" + imei)
        r.hdel('yesterday_step', imei)

